const fs = require('fs')
const path = require('path')

/** @type{String} */
let text = null

/**
 * @param {String} query 
 */
function search(query) {

    console.log('query', query);

    if (!text) {
        text = fs.readFileSync(path.join(__dirname, 'index.txt'), 'utf-8')
    }

    let results = []

    let end = text.indexOf(query)
    while (end > -1) {
        let lineEnd = text.indexOf('\n', end)
        let lineStart = text.lastIndexOf('\n', end)
        let subLine = text.substring(lineStart, lineEnd).trim()
        results.push(subLine)
        end = text.indexOf(query, lineEnd)

        if (results.length > 100) {
            break
        }
    }

    return results

}

module.exports = search